<?php
declare (strict_types=1);

namespace app\api\controller\v1;

use app\api\helpers\Tree;
use app\api\helpers\v1\traits\FileUpload;
use app\api\helpers\v1\traits\SearchDataForModel;
use app\api\model\v1\AdminLog;
use app\api\model\v1\Admins;
use app\api\model\v1\AuthRule;
use app\api\model\v1\Carousel;
use app\api\model\v1\Industry;
use app\api\model\v1\SystemConfig;
use app\api\model\v1\Unit;
use app\api\model\v1\Users;
use app\api\validate\v1\IndustryValidate;
use app\api\validate\v1\UnitValidate;
use app\BaseController;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\Env;
use think\Request;

class System extends BaseController
{

    use SearchDataForModel,FileUpload;



    /**
     * @User: 刘海龙
     * @Date: 2021/8/30
     * @Time: 14:37
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * 获取轮播列表
     */
    public function getCarouselList()
    {
        $limit = $this->request->param('limit', 10);
        $map = [];
        if ($this->request->has('carousel_type') && !empty($this->request->param('carousel_type'))) {
            $map[] = ['carousel_type', '=', $this->request->param('carousel_type')];
        }
        $res = Carousel::where($map)->paginate($limit)->each(function ($item, $key) {
            $item['url_path'] = Env::get('HTTP.http', 'HTTP.default_http') . 'storage/' . $item['path'];
            return $item;
        });
        return $this->response($res);
    }

    /**
     * @param $id
     * @User: 刘海龙
     * @Date: 2021/8/30
     * @Time: 14:47
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 获取唯一信息
     */
    public function getShowCarousel($id)
    {
        $res = Carousel::find($id);
        if (is_null($res)) {
            return $this->response(403, '找不到该资源信息');
        }
        $file = app()->getRootPath() . 'public/storage/' . $res->path;
        if (file_exists($file)) {
            $url = Env::get('HTTP.http', 'HTTP.default_http') . 'storage/' . $res->path;
        } else {
            $url = Env::get('HTTP.http', 'HTTP.default_http') . $res->path;
        }
        $data[] = ['name' => $res->title ?? '暂未', 'url' => $url, 'file' => $res->path];
        $res['img_fileList'] = $data;
        $res['carousel_type'] = $res->carousel_type . '';
        return $this->response($res->toArray());
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/9/2
     * @Time: 18:58
     * @return \think\response\Json
     * 获取轮播图类别
     */
    public function getCarouseType(){
        $res = Carousel::$carouse_type;
        return $this->response($res);
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/8/30
     * @Time: 14:30
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 保存轮播图
     */
    public function saveCarousel()
    {
        $id = $this->request->param('id', 0);
        $data = $this->request->param();
        $data['create_id'] = $this->request->uid; //用户id
        if (intval($id) === 0) {
            Carousel::create($data);
        } else {
            $res = Carousel::find($id);
            if (is_null($res)) {
                return $this->response(403, '数据不存在');
            }
            $res->save($data);
        }
        return $this->response();
    }

    /**
     * @param $id
     * @User: 刘海龙
     * @Date: 2021/8/30
     * @Time: 14:52
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 删除
     */
    public function deleteCarousel($id)
    {
        $res = Carousel::find($id);
        if (is_null($res)) {
            return $this->response(403, '找不到该资源信息');
        }
        if (!empty($res->path)) {
            $file = app()->getRootPath() . 'public/storage/' . $res->path;
            if (file_exists($file)) {
                unlink($file);
            }
        }
        $res->force()->delete();
        return $this->response();
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/8/30
     * @Time: 16:49
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 获取配置
     */
    public function getSystemConfig()
    {
        $res = SystemConfig::select()->toArray();
        $new_data = [];
        foreach ($res as $key => $v) {
            $new_data[$v['name']] = $v['value'];
        }
        if (empty($new_data)) {
            return $this->response(403, "暂未找到配置信息，请添加");
        }
        return $this->response($new_data);
    }


    /**
     * @User: 刘海龙
     * @Date: 2021/8/30
     * @Time: 16:47
     * @return \think\response\Json
     * @throws \Exception
     * 保存配置
     */
    public function saveSystemConfig()
    {
        $data = $this->request->only(['about_content', 'title','default_head','default_bg','mobile','notice_type','notice']);
        $data['default_bg'] = json_encode($data['default_bg'], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); //不转义

        $arr_key = array_keys($data);
        $new_data = [];
        foreach ($arr_key as $key => $value) {
            $new_data[] = [
                'name' => $value,
                'value' => $data[$value]
            ];
        }
        $config = new SystemConfig();
        Db::name('system_config')->delete(true);
        $config->saveAll($new_data);
        return $this->response();
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/9/25
     * @Time: 16:58
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * 数据列表
     */
    public function getIndustryList()
    {
        $limit = $this->request->param('limit', 10);
        $type = $this->request->param('type', 'paginate');
        $map = [];
        if (!$this->is_super){
            $map[] = array('id','=',$this->request->industry_id);
        }
        if ($type === 'no_paginate') {
            $res = Industry::field('id,title')->where($map)->select();
        } else {
            $res = $this->search(new Industry(),$map, $limit, 'asc', []);
        }
        return $this->response($res);
    }


    /**
     * @User: 刘海龙
     * @Date: 2021/9/25
     * @Time: 16:56
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 保存行业and编辑行业
     */
    public function saveIndustry()
    {
        $id = $this->request->param('id', 0);
        try {
            $validator = $this->validate($this->request->param(),
                IndustryValidate::rules($id),
                IndustryValidate::msg());
            if ($validator) {
                $data = $this->request->param();
                $data['create_id'] = $this->request->uid;
                if (intval($id) === 0) {
                    Industry::create($data);
                } else {
                    $res = Industry::find($id);
                    $res->save($data);
                }
                //日志
                AdminLog::record(intval($id) === 0 ? '新增行业' : '编辑行业', $this->request->param(), $this->request->uid, $this->request->username);
                return $this->response();
            }
        } catch (ValidateException $exception) {
            // 验证失败 输出错误信息
            return $this->response(403, $exception->getError());
        }
    }


    /**
     * @param $id
     * @User: 刘海龙
     * @Date: 2021/9/25
     * @Time: 17:08
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 删除
     */
    public function industryDel($id)
    {
        $res = Industry::find($id);
        if (is_null($res)) {
            return $this->response(501, '无法找到数据');
        }
        $res->force()->delete();
        //日志
        AdminLog::record('删除行业', $this->request->param(), $this->request->uid, $this->request->username);
        return $this->response();
    }


    /**
     * @User: 刘海龙
     * @Date: 2021/9/25
     * @Time: 18:03
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 获取单位列表
     */
    public function getUnitList()
    {
        $limit = $this->request->param('limit', 10);
        $type = $this->request->param('unit_type', 'paginate');
        $data = Unit::with(['industry', 'users'])->field('id,pid,unit_title,industry_id')->select()->toArray();

        //超级管理员登录的话！
        //不是超级管理员登录的话
        //不分页的情况下
        if (!$this->is_super) {
            $unit = Unit::find($this->request->unit_id);
            $pid = $unit['pid'];
            $unitData = $this->tree->init($data); //获取当前单位的树
            $ids_arr = $unitData->getChildren($this->request->unit_id,true);
        } else { //超级管理员
            $pid = 0;
            $ids_arr = $data;
        }
        $res = AuthRule::sortMenu($ids_arr,$pid);
//        if ($type === 'no_paginate') {
//            $res = Unit::with(['industry', 'users'])->field('id,pid,unit_title,industry_id')->where([['id','in',$ids_arr]])->select();
//        } else {
//            $data = Unit::with(['industry', 'users'])->field('id,pid,unit_title,industry_id')->where([['id','in',$ids_arr]])->paginate($limit);
//            halt($data);
//            $res = AuthRule::sortMenu($data);
//        }
        return $this->response($res);
    }




    public function readUnitList()
    {
        $data = Unit::field('id,pid,unit_title,attribute')->select()->each(function($item,$key){
            $item['attribute_name'] = Unit::$is_attribute[$item['attribute']];
            return $item;
        })->toArray();
        $unitData = $this->tree->init($data); //获取当前单位的树
        $ids_arr = $unitData->getTreeArray($this->request->unit_id,true);
        return $this->response($ids_arr);
    }


    public function readAttribute(){
        $res = Unit::$is_attribute;
        return $this->response($res);
    }


    /**
     * @User: 刘海龙
     * @Date: 2021/9/25
     * @Time: 17:42
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 保存单位
     */
    public function saveUnit()
    {
        $id = $this->request->param('id', 0);
        try {
            $validator = $this->validate($this->request->param(),
                UnitValidate::rules($id),
                UnitValidate::msg());
            if ($validator) {
                $data = $this->request->param();
                $data['create_id'] = $this->request->uid;
                if (intval($id) === 0) {
                    $parent_id = $this->request->unit_id;
                    if (intval($parent_id) === 0) {
                        $data['level'] = 0;
                    } else {
                        $data['level'] = Unit::find($parent_id)->level + 1;
                    }
                    $data['pid'] = $this->request->unit_id;
                    Unit::create($data);
                } else {
                    $res = Unit::find($id);
                    $res->save($data);
                }
                //日志
                AdminLog::record(intval($id) === 0 ? '新增单位' : '编辑单位', $this->request->param(), $this->request->uid, $this->request->username);
                return $this->response();
            }
        } catch (ValidateException $exception) {
            // 验证失败 输出错误信息
            return $this->response(403, $exception->getError());
        }
    }


    /**
     * @param $id
     * @User: 刘海龙
     * @Date: 2021/9/26
     * @Time: 8:55
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 删除单位
     */
    public function UnitDel($id)
    {
        $res = Unit::find($id);
        if (is_null($res)) {
            return $this->response(501, '无法找到数据');
        }
        $res->force()->delete();
        //日志
        AdminLog::record('删除单位', $this->request->param(), $this->request->uid, $this->request->username);
        return $this->response();
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/10/9
     * @Time: 15:39
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 关于我们
     */
    public function getAboutMeInfo(){
        $res = SystemConfig::where(['name'=>'about_content'])->find()->toArray();
        return $this->response($res);
    }

    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/4/28 8:42
     * @return \think\response\Json
     * 导入用户
     */
    public function importUnitUser(){

        if (!$this->request->file('file')) {
            return $this->response(501, '请选择上传文件');
        }
        $file = $this->request->file('file');

        $result = $this->saveImportExcel($file, 'import_excel', 'stage');

        $is_bool = Users::saveUserExcel($result, 1);
        if ($is_bool) {
            return $this->response();
        } else {
            return $this->response(403, '导入问卷失败');
        }
    }



    public function importUnit(){
        if (!$this->request->file('file')) {
            return $this->response(501, '请选择上传文件');
        }
        $file = $this->request->file('file');
        $result = $this->saveImportUnitExcel($file, 'import_excel', 'multistage');
        $is_bool = Unit::saveUnitExcel($result, 1);
        if ($is_bool) {
            return $this->response();
        } else {
            return $this->response(403, '导入问卷失败');
        }
    }


    public function test(){
       $res = Users::with(['unit'])->whereWeek('create_time')->select()->filter(function (Users $users){
           if(empty($users->unit)){
               return true;
           }
       });
       halt(array_values($res->toArray()));
    }


    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/7/1 10:41
     * @return \think\response\Json
     * 密码重置
     */
    public function passwordReset(){
        $data = $this->request->param();
        $pwdReset =  password_hash('111111',PASSWORD_DEFAULT);
        if (intval($data['type']) === 1){ //重置自己的密码
            $this->user->save(['password'=>$pwdReset]);
        }else{ //重置别人的密码
            $res = Users::where(['mobile'=>$data['mobile']])->findOrEmpty();
            if ($res->isEmpty()){
                return $this->response(404,'手机号不存在');
            }
            $res->save(['password'=>$pwdReset]);
        }
        return $this->response();
    }

    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/7/1 11:01
     * @return \think\response\Json
     * 同步账号信息
     */
    public function syncAccount(){
        return $this->response($this->user);
    }

    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/6/29 10:46
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 单位网点删除并同步到redis中....
     */
    public function syncRedis()
    {
        $redis_key = "unit";
        if ($this->redis->has($redis_key)) {
           $this->redis->delete($redis_key);
        }
        $unit = Unit::select()->toArray();
        foreach ($unit as $key => $value) {
            $this->redis->zadd($redis_key, $value['id'], json_encode($value, JSON_UNESCAPED_UNICODE));
        }
        return $this->response();
    }
}
